<template>
  <el-cascader ref="cascader" v-model="codeArr" :props="propsObj" v-bind="$attrs" style="width:100%" @change="changeHandle"></el-cascader>
</template>
<script>
import { getAdminiDiv } from '@/api/mscInfo'
export default {
  name: 'NativePlace',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    label: {
      type: Array,
      default: () => []
    },
    option: {
      type: String,
      default: 'id'
    }
  },
  data() {
    return {
      propsObj: {
        lazy: true,
        lazyLoad: this.lazyLoad,
        value: this.option,
        label: 'name'
      },
      codeArr: [],
      nameArr: []
    }
  },
  watch: {
    value: {
      handler: function() {
        this.codeArr = this.value
      },
      immediate: true
    }
  },
  methods: {
    lazyLoad(node, resolve) {
      this.nameArr[node.level - 1] = node.label
      this.$emit('update:label', this.nameArr)
      getAdminiDiv({ id: node.value }).then(res => {
        resolve(res.data.map(e => {
          e.leaf = node.level >= 2
          return e
        }))
      })
    },
    changeHandle(v) {
      const nodes = this.$refs.cascader.getCheckedNodes(true)
      this.nameArr = this.getName(nodes[0]).reverse()
      this.$emit('update:label', this.nameArr)
      this.$emit('input', v)
    },
    getName(v) {
      const t = []
      if (v === undefined) {
        return t
      }
      t.push(v.label)
      if (v.parent) {
        t.push(...this.getName(v.parent))
      }
      return t
    }
  }
}
</script>
<style lang='scss' module>
</style>
